package com.mayikt.strategy.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.mayikt.base.BaseApiService;
import com.mayikt.base.BaseResponse;
import com.mayikt.config.AlipayConfig;
import com.mayikt.constant.PayConstant;
import com.mayikt.entity.PaymentChannelEntity;
import com.mayikt.entity.PaymentTransactionEntity;
import com.mayikt.mapper.PaymentTransactionMapper;
import com.mayikt.strategy.PayStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Name AliPayStrategy
 * @Author 枫火
 * @Date 2021/7/14 19:43
 * @Description
 **/
@Component
@Slf4j
public class AliPayStrategy extends BaseApiService implements PayStrategy {

    @Autowired
    private PaymentTransactionMapper paymentTransactionMapper;

    @Override
    public String toPayHtml(PaymentChannelEntity pce, PaymentTransactionEntity pte) {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(pce.getRequestAddress(),
                pce.getMerchantId(), pce.getPrivateKey(), "json",
                AlipayConfig.CHARSET, pce.getPublicKey(), AlipayConfig.SIGN_TYPE);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(pce.getSyncUrl());
        alipayRequest.setNotifyUrl(pce.getAsynUrl());
        String orderId = pte.getOrderId();
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + pte.getPaymentId() + "\","
                + "\"total_amount\":\"" + pte.getPayAmount() / 100 + "\","
                + "\"subject\":\"" + pte.getOrderName() + "\","
                + "\"body\":\"" + pte.getOrderBody() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        try {
            String result = alipayClient.pageExecute(alipayRequest).getBody();

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public BaseResponse<String> verifyOrder(PaymentChannelEntity pce, String paymentId) {
        // 先根据支付id，查询是都已经支付过
        PaymentTransactionEntity pte = paymentTransactionMapper.selectByPaymentId(paymentId);
        if (pte == null) {
            return setResultError("根据支付id没有查询到支付信息");
        }
        if (!(PayConstant.PAY_STAY_STATUS.equals(pte.getPaymentStatus()))) {
            return setResultError("不需要实现补偿");
        }
        //  3.如果在商户端没有支付过情况下，则调用第三方支付接口查询 同步订单状态
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(pce.getRequestAddress(),
                pce.getMerchantId(), pce.getPrivateKey(), "json",
                AlipayConfig.CHARSET, pce.getPublicKey(), AlipayConfig.SIGN_TYPE);
        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        //请二选一设置
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + paymentId + "\"," + "\"trade_no\":\"" + "" + "\"}");
        //请求
        try {
            String result = alipayClient.execute(alipayRequest).getBody();
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject aliPayResponse = jsonObject.getJSONObject("alipay_trade_query_response");
            String payCode = aliPayResponse.getString("code");
            if (!(PayConstant.ALIPAY_PAY_SUCCESS_CODE.equals(payCode))) {
                // 则同步该订单状态
                return setResultError("该支付订单没有在支付宝支付");
            }
            // 修改订单状体
            int updateAliPayResult = paymentTransactionMapper.
                    updatePaymentStatus(PayConstant.PAY_PAID_STATUS + "",
                            paymentId, "ali_pay");
            return updateAliPayResult >= 0 ? setResultSuccess("数据同步为已经支付")
                    : setResultError("系统错误同步失败");
        } catch (Exception e) {
            log.error(">>>verifyOrder()<<", e);
            return setResultError("系统错误同步失败");
        }
    }
}
